package com.wen.sms.controller;

import com.wen.commonutils.ResultEntity;
import com.wen.sms.service.SmsService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author：Win
 * @Date: 2021/6/13 22:50
 * @Description:
 */
@RestController
@RequestMapping("/edu/sms/service")
public class SmsController {
    @Resource
    private SmsService smsService;
    //  将验证码存入redis中并设置有效时间
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("send/{mobile}")
    public ResultEntity sendMessage(@PathVariable("mobile") String mobile) {
//        发送验证码前先从redis中尝试获取验证码,如果存在就返回当前code,不存在就发送短信
        String code;
        code = redisTemplate.opsForValue().get(mobile);
        if (!StringUtils.isEmpty(code))
            return ResultEntity.ok().data("code", code);
//        redis中不存在code,就发送短信
        code = smsService.sendMessage(mobile);
//        将code存入redis中,并设置有效时间
        redisTemplate.opsForValue().set(mobile, code, 5, TimeUnit.MINUTES);
        return ResultEntity.ok().data("code", code);
    }
}
